package com.scuec.trainingmanagementsys.controller;

import com.scuec.trainingmanagementsys.entity.Project;
import com.scuec.trainingmanagementsys.entity.Team;
import com.scuec.trainingmanagementsys.service.ProjectService;
import com.scuec.trainingmanagementsys.service.TeamService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/project")
@CrossOrigin
public class ProjectController {
    @Autowired
    private ProjectService projectService;

    @Autowired
    private TeamService teamService;  // 添加TeamService依赖

    // 添加项目
    @PostMapping("/insert")
    public Map<String, Object> addProject(@RequestBody Project project) {
        Map<String, Object> result = new HashMap<>();
        try {
            // 验证必填字段
            if (project.getProjectName() == null || project.getProjectName().trim().isEmpty()) {
                result.put("success", false);
                result.put("message", "项目名称不能为空");
                return result;
            }

            // 验证日期
            if (project.getStartDate() == null || project.getEndDate() == null) {
                result.put("success", false);
                result.put("message", "开始日期和结束日期不能为空");
                return result;
            }

            // 验证开始日期 <= 结束日期
            if (project.getStartDate().after(project.getEndDate())) {
                result.put("success", false);
                result.put("message", "开始日期不能晚于结束日期");
                return result;
            }

            // 验证组数
            if (project.getGroupCount() == null || project.getGroupCount() < 1) {
                result.put("success", false);
                result.put("message", "组数不能小于1");
                return result;
            }

            // 设置默认状态为"进行中"
            project.setProjectStatus("进行中");
            // 设置可用名额为0（不再使用）
            project.setAvailableSlots(0);

            // 调用 Service 层插入数据
            int projectId = projectService.addProject(project);

            if (projectId > 0) {
                // 创建小组
                int groupCount = project.getGroupCount();
                for (int i = 1; i <= groupCount; i++) {
                    Team team = new Team();
                    team.setTeamName("第" + getChineseNumber(i) + "组");  // 生成中文组名
                    team.setProjectID(projectId);
                    team.setLeaderID(null); // 组长ID暂时设为null

                    // 创建小组
                    teamService.addTeam(team);
                }

                result.put("success", true);
                result.put("message", "项目创建成功");
                result.put("projectId", projectId);
            } else {
                result.put("success", false);
                result.put("message", "项目创建失败");
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "日期格式错误，请使用 yyyy-MM-dd 格式");
            e.printStackTrace();
        }
        return result;
    }

    // 辅助方法：将数字转换为中文
    private String getChineseNumber(int number) {
        String[] chineseNumbers = {"一", "二", "三", "四", "五", "六", "七", "八", "九", "十"};
        if (number >= 1 && number <= 10) {
            return chineseNumbers[number - 1];
        } else if (number > 10) {
            return "十" + chineseNumbers[number - 11];
        }
        return String.valueOf(number);
    }

    // 删除项目
    @DeleteMapping("delete/{projectId}")
    public Map<String, Object> deleteProject(@PathVariable Integer projectId) {
        Map<String, Object> result = new HashMap<>();
        int rows = projectService.deleteProject(projectId);
        if (rows > 0) {
            result.put("success", true);
            result.put("message", "项目删除成功");
        } else {
            result.put("success", false);
            result.put("message", "项目删除失败");
        }
        return result;
    }

    // 更新项目
    @PutMapping("/update/{projectId}")
    public Map<String, Object> updateProject(@PathVariable Integer projectId, @RequestBody Project project) {
        Map<String, Object> result = new HashMap<>();
        try {
            project.setProjectId(projectId);
            // 确保状态字段正确设置
            if (project.getProjectStatus() == null) {
                project.setProjectStatus("进行中");
            }
            int rows = projectService.updateProject(project);
            result.put("code", rows > 0 ? 200 : 500);
            result.put("message", rows > 0 ? "项目更新成功" : "项目更新失败");
        } catch (Exception e) {
            result.put("code", 500);
            result.put("message", "日期格式错误，请使用 yyyy-MM-dd 格式");
        }
        return result;
    }

    // 根据项目ID获取项目信息
    @GetMapping("/{projectId}")
    public Map<String, Object> getProject(@PathVariable Integer projectId) {
        Map<String, Object> result = new HashMap<>();
        try {
            Project project = projectService.getProject(projectId);
            result.put("code", 200);
            result.put("data", project);
            result.put("message", "success");
        } catch (Exception e) {
            result.put("code", 500);
            result.put("message", "获取项目信息失败");
            e.printStackTrace();
        }
        return result;
    }
    // 获取项目下所有小组
    @GetMapping("/{projectId}/teams")
    public Map<String, Object> getTeamsByProjectId(@PathVariable Integer projectId) {
        Map<String, Object> result = new HashMap<>();
        try {
            List<Map<String, Object>> teams = projectService.getTeamsByProjectId(projectId);
            result.put("code", 200);
            result.put("data", teams);
            result.put("message", "success");
        } catch (Exception e) {
            result.put("code", 500);
            result.put("message", "获取小组失败");
            e.printStackTrace();
        }
        return result;
    }

    // 获取所有项目
    @GetMapping("/list")
    public ResponseEntity<Map<String, Object>> getAllProjects() {
        Map<String, Object> result = new HashMap<>();
        try {
            List<Project> projects = projectService.getAllProjects();
            result.put("code", 200);
            result.put("data", projects);
            result.put("message", "success");
            return new ResponseEntity<>(result, HttpStatus.OK);
        } catch (Exception e) {
            result.put("code", 500);
            result.put("message", "获取项目列表失败: " + e.getMessage());
            return new ResponseEntity<>(result, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    // 获取项目总数
    @GetMapping("/count")
    public Map<String, Object> getProjectCount() {
        Map<String, Object> result = new HashMap<>();
        int count = projectService.getProjectCount();
        result.put("code", 200);
        result.put("data", count);
        result.put("message", "success");
        return result;
    }

    // 根据教师ID获取项目（应该在Controller中）
    @GetMapping("/teacher/{teacherId}")
    public Map<String, Object> getProjectsByTeacherId(@PathVariable Integer teacherId) {
        Map<String, Object> result = new HashMap<>();
        try {
            List<Project> projects = projectService.getProjectsByTeacherId(teacherId);
            result.put("code", 200);
            result.put("data", projects);
            result.put("message", "success");
        } catch (Exception e) {
            result.put("code", 500);
            result.put("message", "获取项目失败");
            e.printStackTrace();
        }
        return result;
    }

    // 更新项目状态（应该在Controller中）
    @PutMapping("/updateStatus/{projectId}")
    public Map<String, Object> updateProjectStatus(@PathVariable Integer projectId, @RequestBody Map<String, String> statusMap) {
        Map<String, Object> result = new HashMap<>();
        try {
            String status = statusMap.get("status");
            int rows = projectService.updateProjectStatus(projectId, status);
            result.put("success", rows > 0);
            result.put("message", rows > 0 ? "状态更新成功" : "状态更新失败");
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "状态更新失败");
            e.printStackTrace();
        }
        return result;
    }

    // 保存项目评分（应该在Controller中）
    @PutMapping("/saveScores/{projectId}")
    public Map<String, Object> saveProjectScores(@PathVariable Integer projectId, @RequestBody Map<String, Object> scoresMap) {
        Map<String, Object> result = new HashMap<>();
        try {
            // 这里可以添加保存评分的逻辑
            result.put("success", true);
            result.put("message", "评分保存成功");
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "评分保存失败");
            e.printStackTrace();
        }
        return result;
    }

    // 根据项目名称搜索项目
    @GetMapping("/search")
    public Map<String, Object> searchProjectsByName(@RequestParam String projectName) {
        Map<String, Object> result = new HashMap<>();
        try {
            List<Project> projects = projectService.searchProjectsByName(projectName);
            result.put("code", 200);
            result.put("data", projects);
            result.put("message", "success");
        } catch (Exception e) {
            result.put("code", 500);
            result.put("message", "搜索项目失败");
            e.printStackTrace();
        }
        return result;
    }

    // 批量删除项目
    @PostMapping("/batchDelete")
    public Map<String, Object> batchDeleteProjects(@RequestBody Map<String, List<Integer>> request) {
        Map<String, Object> result = new HashMap<>();
        try {
            List<Integer> ids = request.get("ids");
            int deletedCount = projectService.batchDeleteProjects(ids);
            result.put("success", true);
            result.put("deletedCount", deletedCount);
            result.put("message", "成功删除 " + deletedCount + " 个项目");
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "批量删除失败: " + e.getMessage());
            e.printStackTrace();
        }
        return result;
    }


}